package com.bluefox.uac.filter;

import com.bluefox.common.web.dto.result.ResultDTO;
import com.bluefox.common.web.utils.JsonUtils;
import com.bluefox.common.webauth.filter.DefaultAuthenticationSuccessHandler;
import com.bluefox.uac.security.CustomAuthenticationToken;
import com.bluefox.uac.security.LoginUserBean;
import lombok.Getter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

/**
 * @author SF  创建时间: 2019/12/4 16:47
 */
public class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler {
    @Getter
    class ReturnToken {

        /**
         * 用户编码
         */
        private final String userId;

        /**
         * 用户姓名
         */
        private final String username;

        /**
         * 用户角色列表
         */
        private final Collection<SimpleGrantedAuthority> roles;

        private final List<String> roleCodes;
        private final String nonceToken;

        public ReturnToken(final LoginUserBean bean, final String token) {
            this.username = bean.getUsername();
            this.roles = bean.getRoles();
            this.nonceToken = token;
            this.userId = bean.getUserId();
            this.roleCodes = bean.getRoleCodes();
        }

    }

    // 重新认证成功接口
    @Override
    protected void handle(final HttpServletRequest request, final HttpServletResponse response,
                          final Authentication authentication)
            throws IOException, ServletException {
        final CustomAuthenticationToken customToken = (CustomAuthenticationToken) authentication;
        if ((request.getContentType() == null) || request.getContentType().contains("application/json")) {
            response.addHeader("Content-Type", "application/json;charset=UTF-8");
            final PrintWriter writer = response.getWriter();
            final ResultDTO<?> rs =
                    ResultDTO.success(new ReturnToken(customToken.getDetails(), customToken.getNonceToken()));
            writer.write(JsonUtils.pojoToJson(rs));
        }
        final String targetUrl = request.getParameter("redirect");

        if ((targetUrl != null) && response.isCommitted()) {
            this.logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        }

        super.getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}
